package com.nut.spp.service.impl;

import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.nut.spp.baidu.RegionResult;
import com.nut.spp.common.Result;
import com.nut.spp.entity.AdapayRegion;
import com.nut.spp.mapper.AdapayRegionMapper;
import com.nut.spp.service.AdapayRegionService;
import com.nut.spp.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
@Slf4j
public class AdapayRegionServiceImpl implements AdapayRegionService {

    @Autowired
    private AdapayRegionMapper adapayRegionMapper;

    public static final String PAY_REGION = "https://cdn.cloudpnr.com/adapayresource/documents/Adapay%E7%9C%81%E5%B8%82%E7%BC%96%E7%A0%81%EF%BC%88%E5%9B%9B%E4%BD%8D%EF%BC%89.json";

    @Override
    public void generateRegion() {

        String response = HttpRequest.get(PAY_REGION).execute().body();
        JsonNode obj = JacksonUtils.toObj(response);

        Iterator<JsonNode> elements = obj.elements();
        while (elements.hasNext()) {

            JsonNode next = elements.next();

            AdapayRegion region = new AdapayRegion();
            region.setPid(0);
            region.setName(next.get("title").asText());
            region.setCode(next.get("value").asText());
            region.setType(1);
            adapayRegionMapper.insert(region);

            Iterator<JsonNode> cities = next.get("cities").elements();
            while (cities.hasNext()) {
                JsonNode city = cities.next();

                AdapayRegion region2 = new AdapayRegion();
                region2.setPid(region.getId());
                region2.setName(city.get("title").asText());
                region2.setCode(city.get("value").asText());
                region2.setType(2);
                adapayRegionMapper.insert(region2);

            }

        }
    }

    private void generateData(List<RegionResult.District> districts, Integer pid) {
        if (districts.isEmpty()) {
            return;
        }
        for (RegionResult.District district : districts) {

            AdapayRegion region = new AdapayRegion();
            region.setPid(pid);
            region.setName(district.getName());
            region.setCode(district.getCode());
            region.setType(district.getLevel());
            adapayRegionMapper.insert(region);

            if (region.getType() != 3 && district.getDistricts() != null && !district.getDistricts().isEmpty()) {
                generateData(district.getDistricts(), region.getId());
            }
        }
    }

    @Override
    public Result<List<AdapayRegion>> list(Integer pid) {
        List<AdapayRegion> list = adapayRegionMapper.selectByPid(pid);
        return Result.ok(list);
    }

}